package cn.flying.cloud.task.core.quartz.listener;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import cn.flying.cloud.task.service.TaskJobLogService;

/**
 * @author: admin
 * @date: 2024年01月15日 16:25
 * @version: 1.0
 */
@Component
public class QuartzJobListener implements JobListener {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TaskJobLogService jobLogService;

    /**
     * 监听器名称
     */
    @Override
    public String getName() {
        return "quartz-job-listener";
    }

    /**
     * Scheduler在JobDetail将要被执行时调用这个方法
     *
     * @param context
     * @see #jobExecutionVetoed(JobExecutionContext)
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        logger.info("开始调度任务!任务名称：{}，所属分组：{}", jobKey.getName(), jobKey.getGroup());
        context.getMergedJobDataMap().put("startTime", LocalDateTime.now());
    }

    /**
     * Scheduler在JobDetail即将被执行，但又被TriggerListener否决时会调用该方法
     *
     * @param context
     * @see #jobToBeExecuted(JobExecutionContext)
     */
    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        logger.info("job调度完成，但是被Trigger拒绝!任务名称：{}，所属分组：{}", jobKey.getName(), jobKey.getGroup());
    }

    /**
     * Scheduler在JobDetail被执行之后调用这个方法
     *
     * @param context
     * @param jobException
     */
    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        JobDetail jobDetail = context.getJobDetail();
        JobKey jobKey = jobDetail.getKey();
        String instanceId = context.getFireInstanceId();
        logger.info("job执行完成!任务名称：{}，所属分组：{}，执行实例：{}", jobKey.getName(), jobKey.getGroup(), instanceId);
    }
}
